package org.gosdt.ew.model;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

import org.gosdt.ew.db.EWDataBase;

/**
 * Class describe data base entity Topic allow select, insert and update entity
 * 
 * @author anton
 * 
 */
public class Topic extends DataBaseAccess {
	private static final String TABLE_NAME = "Topic";
	// true if entity is't in db
	private static boolean isNew = true;

	private String name;
	private String language;

	public Topic(String name, String language) {
		super(TABLE_NAME);
		this.name = name;
		this.language = language;
		if (isNew) {
			if (!isTopicExists())
				insertCurrentRecord();
		}
	}

	public String getTopicName() {
		return name;
	}

	public String getTopicLanguage() {
		return language;
	}

	private boolean isTopicExists() {
		String query = "Select * from " + TABLE_NAME + " where name = '"
				+ name.toLowerCase() + "' and stadyLanguage = '"
				+ language.toLowerCase() + "'";
		try {
			EWDataBase db = EWDataBase.getInstance();
			ResultSet rs = db.getConn().prepareStatement(query).executeQuery();
			while (rs.next()) {
				rs.close();
				return true;
			}
			rs.close();
		} catch (Exception exept) {
			exept.printStackTrace();
		}
		return false;
	}

	public static ArrayList<Topic> getTopicListByWord(String operation,
			String value) {
		try {
			HashMap<String, String> keys = new HashMap<String, String>();
			keys.put("operation", operation);
			keys.put("value", value);
			ResultSet rs = getMyTopicListByWord(keys);
			return getTopicListByRS(rs);
		} catch (SQLException exept) {
			exept.printStackTrace();
			isNew = true;
			return null;
		}
	}

	public static ArrayList<Topic> getTopicList(String operation, String value,
			String stadyLanguage) {
		try {
			HashMap<String, String> keys = new HashMap<String, String>();
			keys.put("operation", operation);
			keys.put("value", value);
			keys.put("stadyLanguage", stadyLanguage);
			ResultSet rs = getMyListByDetail(keys);
			return getTopicListByRS(rs);
		} catch (SQLException exept) {
			exept.printStackTrace();
			isNew = true;
			return null;
		}
	}

	private static ArrayList<Topic> getTopicListByRS(ResultSet rs)
			throws SQLException {
		ArrayList<Topic> list = new ArrayList<Topic>();
		isNew = false;
		while (rs.next()) {
			Topic topic = new Topic(rs.getString("name"),
					rs.getString("stadyLanguage"));
			list.add(topic);
		}
		isNew = true;
		rs.close();
		return list;
	}

	private static final ResultSet getMyTopicListByWord(
			HashMap<String, String> keys) {
		String query = "Select " + TABLE_NAME + ".* from " + TABLE_NAME
				+ " join WordInTopic on " + "WordInTopic.topicName = "
				+ TABLE_NAME + ".name and WordInTopic.wordID ";
		query += keys.get("operation");
		query += keys.get("value");
		try {
			EWDataBase db = EWDataBase.getInstance();
			return db.getConn().prepareStatement(query).executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}

	private static final ResultSet getMyListByDetail(
			HashMap<String, String> keys) {
		String query = "Select * from " + TABLE_NAME + " where name ";
		query += keys.get("operation") + " ";
		query += keys.get("value") + " ";
		query += "and stadyLanguage = '" + keys.get("stadyLanguage") + "'";
		try {
			EWDataBase db = EWDataBase.getInstance();
			return db.getConn().prepareStatement(query).executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}

	public int deleteCurrentRecord() {
		ArrayList<String> keys = new ArrayList<String>();
		keys.add("name = '" + name + "'");
		keys.add("stadyLanguage = '" + language.toLowerCase() + "'");
		return super.deleteOneRecord(keys);
	}

	public int deleteWordsTopics(Vocabulary word) {
		String insertSQL = "DELETE FROM WordInTopic WHERE wordID = "
				+ Integer.toString(word.getId());
		try {
			java.sql.PreparedStatement ps = db.getConn().prepareStatement(
					insertSQL);
			ps.execute();
			return ps.getUpdateCount();
		} catch (SQLException e) {
			e.printStackTrace();
			return -1;
		}
	}

	private int insertCurrentRecord() {
		HashMap<String, String> insertValues = new HashMap<String, String>();
		insertValues.put("name".toUpperCase(), name.toLowerCase());
		insertValues.put("stadyLanguage".toUpperCase(),
				language.toLowerCase());
		return super.insertOneRecord(insertValues);
	}

	public boolean equals(Object obj) {
		if (obj == null)
			return false;

		if (obj == this)
			return true;

		if (obj instanceof Topic) {
			Topic tmp = (Topic) obj;
			if (tmp.getTopicName().equals(name)
					&& tmp.getTopicLanguage().equals(language))
				return true;
		}
		return false;
	}

	/**
	 * join current topic and one word
	 * 
	 * @param word
	 *            - word for adding to topic
	 */
	public void joinWordAndTopic(Vocabulary word) {
		String insertSQL = "INSERT INTO WordInTopic VALUES ('"
				+ name.toLowerCase() + "', "
				+ Integer.toString(word.getId()) + ")";

		try {
			db.getConn().prepareStatement(insertSQL).execute();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	@Deprecated
	protected final ResultSet getListByDetail(HashMap<?, ?> keys) {
		throw new UnsupportedOperationException();
	}

}
